﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using System.Web.Security;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Tools.Log;
using Senparc.Weixin.MP.AdvancedAPIs;
using Lion.WeiXin.Core;
namespace Lion.WeiXin.Controllers
{
    [WeChatFilter]
    /// <summary>
    /// 微信产品
    /// </summary>
    public class WeChatProductController : Controller
    {
        DBContext db = new DBContext();

        //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf4905639eca44d4e&redirect_uri=http%3a%2f%2fwww.mhsg100.com%2fWeChatProduct%2fIndex&response_type=code&scope=snsapi_base&state=123#wechat_redirect

        public ActionResult Index()
        {

            // //模拟微信用户过来测试   // 信仰   oCtEus-broReU00m3LIKrf_fWVFg
            //// string openid = "oCtEus3ZQj2zoA0zBiAvP-OLhkiA";
            // string openid = Request.QueryString["openid"];  //此代码提供测试通道

            //WeChatUserModel wcUser = iwcUser.GetModel(CurrentUser.OpenId);
            //if (wcUser != null)
            //{
            //    Handler.CookieHelper<WeChatUserModel>.SaveCookie(KeysEnum.WeChatUser.ToString(), wcUser);
            //    ViewData[KeysEnum.WeChatUser.ToString()] = wcUser;
            //    LogHelper.Info("微信用户本地信息保存成功! openid={0},cardCode={1}", wcUser.OpenId, wcUser.VipCardCode);

            //    //看是否注册用户
            //    VipCardModel vipCard = ivip.GetModel(wcUser.VipCardCode);
            //    if (vipCard != null)
            //    {
            //        DictionaryModel dic = idic.GetModel(vipCard.Dic_CardType);
            //        decimal discount = decimal.Parse(dic.Parameter);
            //        vipCard.Discount = discount;
            //        //保存VipCard Cookie
            //        Handler.CookieHelper<VipCardModel>.SaveCookie(KeysEnum.VipCard.ToString(), vipCard);
            //    }
            //}

            //加载         
            List<ProductModel> list = db.Products.GetList(string.Empty);           
            //推荐产品
            List<ProductModel> topProducts = list.Where(n => n.IsRecommend == 1).OrderByDescending(n => n.Last_Update_Date).ToList();
            //热销产品
            List<ProductModel> hotProducts = list.OrderByDescending(n => n.Sale).ToList();

            ViewData["hotPro"] = hotProducts;
            ViewData["topPro"] = topProducts;

            //产品分类 
            List<DictionaryModel> categorys = db.Dictionarys.GetList("dic_key like '100%' and len(dic_key)=6");
            ViewData["categorys"] = categorys;

            return View();
        }

        public ActionResult ProductList(int typeId)
        {
            //加载           
            DictionaryModel dic = db.Dictionarys.GetModel(typeId);
            List<ProductModel> list = new List<ProductModel>();
            try
            {
                list = db.Products.GetList("Dic_ProductType=" + typeId.ToString());

            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "产品列表出错");

            }
            list = list.OrderByDescending(n => n.Sale).ToList();
            ViewBag.ProductType = dic.Dic_Value;
            return View(list);
        }

        public ActionResult Details(string ID)
        {
            int productID = 0;
            ProductModel model = new ProductModel();
            if (!string.IsNullOrEmpty(ID))
            {
                productID = int.Parse(ID);
                model = db.Products.GetModel(productID);
                //默认用户会员折扣显示
                model.VipPrice = 0;
                model.Discount = 1;
                model.IsVip = false;

                //微信用户如果是注册会员，则用会员折扣显示单价
                WeChatUserModel wcUser = CurrentUser.WXUser;
                VipCardModel vipCard = db.VipCards.GetModel(wcUser.VipCardCode);
                if (vipCard != null)
                {
                    DictionaryModel dic = db.Dictionarys.GetModel(vipCard.Dic_CardLevel);
                    decimal discount = decimal.Parse(dic.Parameter);
                    model.VipPrice = model.Price * discount;
                    model.Discount = discount;
                    model.IsVip = true;

                    vipCard.Discount = discount;
                }
            }
            return View(model);
        }


        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public ActionResult AddToShoppingCart(int productId)
        {
            ProductModel item = db.Products.GetModel(productId);
            Order_DetailsModel orderProduct = new Order_DetailsModel();
            orderProduct.Pro_ID = productId;
            orderProduct.ProductName = item.Name;
            orderProduct.Price = item.Price;
            orderProduct.Quantity = 1;
            orderProduct.Image = item.Image;
            //查询当前会员卡的折扣
            VipCardModel curVip = curVip = GetDiscountByCardCode(CurrentUser.WXUser.VipCardCode);
            
            //根据是否会员用户启用不同折扣
            if (curVip != null)
            {
                orderProduct.Discount = curVip.Discount;  //会员折扣
                orderProduct.BuyPrice = item.Price * curVip.Discount;  //会员价
            }
            else
            {
                orderProduct.Discount = item.Discount;
                orderProduct.BuyPrice = item.Price * item.Discount;
            }

            // 创建cooke 来保存购物车数据
            List<Order_DetailsModel> shoppingList = Handler.CookieHelper<List<Order_DetailsModel>>.GetCookie(KeysEnum.ShoppingCart.ToString());
            //查找是否有相同货物
            if (shoppingList != null)
            {
                if (shoppingList.Exists(n => n.Pro_ID == productId))
                {
                    shoppingList.FirstOrDefault(n => n.Pro_ID == productId).Quantity += 1;
                }
                else
                {
                    shoppingList.Add(orderProduct);
                }
            }
            else
            {
                shoppingList = new List<Order_DetailsModel>();
                shoppingList.Add(orderProduct);
            }

            //保存cookie 数据
            Handler.CookieHelper<List<Order_DetailsModel>>.SaveCookie(KeysEnum.ShoppingCart.ToString(), shoppingList);

            return Content("OK");
        }

        public ActionResult DeleteFromShoppingCart(int productId)
        {
            // 创建cooke 来保存购物车数据
            List<Order_DetailsModel> shoppingList = new List<Order_DetailsModel>();

            shoppingList = Handler.CookieHelper<List<Order_DetailsModel>>.GetCookie(KeysEnum.ShoppingCart.ToString());
            if (shoppingList == null)
            {
                //购物车为空，不可能删除数据
                return Content("购物车是空的");
            }
            else
            {
                //删除
                for (int i = 0; i < shoppingList.Count; i++)
                {
                    if (shoppingList[i].Pro_ID == productId)
                    {
                        shoppingList.RemoveAt(i);
                    }
                }

                Handler.CookieHelper<List<Order_DetailsModel>>.SaveCookie(KeysEnum.ShoppingCart.ToString(), shoppingList);

                return Content("OK");
            }


        }

        /// <summary>
        /// 购物车
        /// </summary>
        /// <returns></returns>
        public ActionResult ShoppingCart()
        {

            List<Order_DetailsModel> shoppingList = Handler.CookieHelper<List<Order_DetailsModel>>.GetCookie(KeysEnum.ShoppingCart.ToString());
            if (shoppingList != null)
            {
                ViewData[KeysEnum.Total.ToString()] = shoppingList.Sum(n => n.BuyPrice * n.Quantity);
            }
            else
            {
                shoppingList = new List<Order_DetailsModel>();
                ViewData[KeysEnum.Total.ToString()] = 0;
            }
            //获取当前用户cokie中的信息
            WeChatUserModel wcUser = CurrentUser.WXUser;
            ViewData[KeysEnum.VipCard.ToString()] = null;
            ViewData[KeysEnum.NickName.ToString()] = CurrentUser.WXUser.NickName;
            if (!string.IsNullOrEmpty(wcUser.VipCardCode))
            {
                VipCardModel vipUser = db.VipCards.GetModel(wcUser.VipCardCode);
                //查询当前卡适用折扣
                DictionaryModel cardType = db.Dictionarys.GetModel(vipUser.Dic_CardLevel);
                vipUser.Discount = decimal.Parse(cardType.Parameter);
                ViewData[KeysEnum.VipCard.ToString()] = vipUser;
                if(vipUser!=null&& !string.IsNullOrEmpty(vipUser.RealName))
                {
                    ViewData[KeysEnum.NickName.ToString()] = vipUser.RealName;
                }
            }
            return View(shoppingList);
        }



        /// <summary>
        /// 支付账单
        /// </summary>
        /// <param name="buyItems">购买服务</param>
        /// <param name="buyer">购买人</param>
        /// <param name="password">支付密码</param>
        /// <param name="phone">联系电话</param>
        /// <param name="note">接引地址备注</param>
        /// <param name="appointment">预约时间</param>
        /// <returns></returns>
        public ActionResult PayBill(string buyItems, string buyer, string password, string phone, string note, DateTime appointment)
        {
            //卡上余额是否够
            PayMsg msg = new PayMsg();
            string cardCode = buyer;
            string cardpwd = password;
            string[] shopItems = buyItems.TrimEnd('|').Split('|');

            VipCardModel vipUser = db.VipCards.GetModel(cardCode);
            if (vipUser == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在" });
            }
            //密码长度如果与加密不一致，加密再判断
            if (vipUser.Password.Length != cardpwd.Length)
            {
                //如果长度不等，可能是原始密码，先加密
                cardpwd = FormsAuthentication.HashPasswordForStoringInConfigFile(cardpwd, "MD5");
            }
            if (vipUser.Password != cardpwd)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "密码不正确" });
            }
            if (vipUser.Dic_CardType == CardTypeEnum.计次卡.ToString())
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "计次卡不能在线购买" });   
            }
            // 查询当前vipcard 的等级折扣
            IDictionary idic = new DictionaryDAO();
            DictionaryModel cardType = idic.GetModel(vipUser.Dic_CardLevel);
            decimal userDiscount = decimal.Parse(cardType.Parameter);

            //查询购买的商品
            List<Order_DetailsModel> shoppingList = new List<Order_DetailsModel>();
            foreach (string strItem in shopItems)
            {
                string[] data = strItem.Split(',');
                int productId = int.Parse(data[0]);
                int quantity = int.Parse(data[1]);
                ProductModel item = db.Products.GetModel(productId);
                Order_DetailsModel orderProduct = new Order_DetailsModel();
                orderProduct.Pro_ID = productId;
                orderProduct.ProductName = item.Name;
                orderProduct.Price = item.Price;
                orderProduct.Quantity = quantity;
                orderProduct.Image = item.Image;
                //采用当前用户卡号的折扣
                orderProduct.Discount = userDiscount;
                orderProduct.BuyPrice = item.Price * userDiscount;
                shoppingList.Add(orderProduct);
            }

            decimal orderTotal = shoppingList.Sum(n => n.BuyPrice * n.Quantity);
            if (vipUser.Balance - orderTotal < 0)
            {
                string errMsg = string.Format("当前卡号[{0}]余额:{1},余额不足！", cardCode, vipUser.Balance);
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = errMsg });
            }

            // 保存订单，
            OrderModel model = new OrderModel();
            //自动产生订单编号，时间+随机数
            model.Code = Tools.StringHelper.CreateNewOrderId(buyer);
            model.Buyer = buyer;  //卡用户
            model.Creator = "System"; //默认系统用户
            model.CreateDate = DateTime.Now;
            model.PayType = OrderPayTypeEnum.储值卡.ToString();
            model.ComeFrom = OrderComeFrom.微信.ToString();
            model.LastUpdateDate = DateTime.Now;
            model.Total = orderTotal;
            model.Payment = orderTotal;
            model.PrePay = 0;
            model.Buyer_Phone = phone;
            model.Buyer_Note = note;
            model.Buyer_Appointment = appointment;
            model.LastUpdateDate = DateTime.Now;
            model.Status = (int)OrderStateEnum.已支付; //已在线支付，但未到店里消费服务
            IOrder iorder = new OrderDAO();
            try
            {
                //添加订单
                int newOrderID = iorder.Add(model, shoppingList);
                //支付订单 
                iorder.PayBill(model);
                //记录日志
                VipCardUseLogHelper.WriteLog(model.Buyer, "支付订单", VipCardUseEnum.消费, model.Code, model.Payment);
                //订单保存成功，清空购物车
                Handler.CookieHelper<List<Order_DetailsModel>>.Clear(KeysEnum.ShoppingCart.ToString());

                //下发短信提示
                if (Config.IsOpenSMS)
                {
                    Sms.ISendSms isend = new Sms.SendSMS();
                    isend.SendMsg(vipUser.Phone, "【美好时光】恭喜你预约成功！,订单编号[" + model.Code + "],如有疑问请联系 139******。");
                }
                else
                {
                    LogHelper.Info("用户[{0}],预约成功订单编号[{1}]!,短信配置为不下发.", vipUser.Phone, model.Code);
                }

                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "支付成功" });
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "支付失败");
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "支付失败" });
            }

        }

        public ActionResult MyOrder()
        {
            VipCardModel vipUser = db.VipCards.GetModel(CurrentUser.WXUser.VipCardCode);

            List<OrderModel> models = new List<OrderModel>();
            if (vipUser != null)
            {
                IOrder iorder = new OrderDAO();
                models = iorder.GetList("Buyer='" + vipUser.Code + "'").OrderByDescending(n => n.AID).ToList();
            }
            return View(models);
        }

        public ActionResult BindVipCard()
        {
            return View();
        }

        public ActionResult SaveBind(FormCollection form)
        {
            VipCardModel inputData = new VipCardModel();
            UpdateModel<VipCardModel>(inputData);
            if (inputData.Password != inputData.Password2)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "两次密码不一致!" });
            }

            VipCardModel vipUser = db.VipCards.GetModel(inputData.Code);
            if (vipUser == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号或密码不正确!" });
            }

            if (vipUser.Password != FormsAuthentication.HashPasswordForStoringInConfigFile(inputData.Password, "MD5"))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号或密码不正确!" });
            }

            WeChatUserModel wcUser = CurrentUser.WXUser;
            //绑定卡号
            wcUser.VipCardCode = inputData.Code;
            IWeChatUser iwcUser = new WeChatUserDAO();
            iwcUser.Update(wcUser);

            //修改卡号基本信息
            if (!string.IsNullOrEmpty(inputData.RealName))
            {
                vipUser.RealName = inputData.RealName;
            }
            vipUser.Phone = inputData.Phone;
            vipUser.Last_Update_Date = DateTime.Now;
            //保存修改
            db.VipCards.Update(vipUser);

            return Json(new { code = SaveStateEnum.OK.ToString(), msg = "绑定成功!" });
        }

        /// <summary>
        /// 解除卡号绑定
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UnBindVipCard()
        {
            //未绑定卡号用户先去绑定界面
            WeChatUserModel wcUser = CurrentUser.WXUser;
            if (string.IsNullOrEmpty(wcUser.VipCardCode))
            {
                return RedirectToAction("BindVipCard");
            }           

            return View(wcUser);
        }

        public JsonResult SaveUnBind(string openid, string cardCode, string password)
        {
            //验证卡密，
            VipCardModel cardModel = db.VipCards.GetModel(cardCode);
            // 解除绑定
            if (cardModel == null)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "卡号不存在!" });
            }
            //密码长度如果与加密不一致，加密再判断
            if (cardModel.Password.Length != password.Length)
            {
                //如果长度不等，可能是原始密码，先加密
                password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            }
            if (cardModel.Password != password)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "密码不正确!" });
            }
            WeChatUserModel wcUser = CurrentUser.WXUser;
            //解除绑定
            wcUser.VipCardCode = string.Empty;
            if (db.WeChatUsers.Update(wcUser))
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "解除绑定成功!" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "操作失败请稍后重试!" });
            }
        }


        [HttpGet]
        /// <summary>
        /// 显示修改密码界面
        /// </summary>
        /// <param name="code">微信验证返回的code</param>
        /// <param name="state">微信验证返回的状态参数</param>
        /// <returns></returns>
        public ActionResult ChangePassword()
        {
            //获取当前用户的卡号
            VipCardModel model = db.VipCards.GetModel(CurrentUser.WXUser.VipCardCode);
            return View(model);
        }

        public ActionResult SavePassword(string cardCode, string oldPassword, string newPassword, string newPassword2)
        {
            string errorMsg = string.Empty;
            if (newPassword != newPassword2)
            {
                errorMsg = "两次密码不一致";
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = errorMsg });
            }
            if (string.IsNullOrEmpty(cardCode))
            {
                errorMsg = "卡号为空";
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = errorMsg });
            }
            VipCardModel model = db.VipCards.GetModel(cardCode);
            if (model == null)
            {
                errorMsg = "卡号不存在";
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = errorMsg });
            }
            //密码长度如果与加密不一致，加密再判断
            if (model.Password.Length != oldPassword.Length)
            {
                //如果长度不等，可能是原始密码，先加密
                oldPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(oldPassword, "MD5");
            }
            if (model.Password != oldPassword)
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "密码或卡号不正确" });
            }
            //修改密码
            newPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(newPassword, "MD5");
            int rows = db.VipCards.ResetPassword(cardCode, newPassword);
            if (rows > 0)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), msg = "修改成功" });
            }
            else
            {
                return Json(new { code = SaveStateEnum.NO.ToString(), msg = "修改失败，请稍后重试" });
            }
        }


        /// <summary>
        /// 获取当前用户的VIPCard，如果没办理，返回null
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private VipCardModel GetDiscountByCardCode(string cardCode)
        {

            VipCardModel vipCard = db.VipCards.GetModel(cardCode);
            if (vipCard == null)
            {
                return null;
            }

            DictionaryModel dic = db.Dictionarys.GetModel(vipCard.Dic_CardLevel);
            decimal discount = decimal.Parse(dic.Parameter);
            vipCard.Discount = discount;
            return vipCard;

        }
    }
}
